package fts_test.lib;

import iboxdb.localserver.*;
import ftserver.fts.*;
import java.util.concurrent.*;

public class iboxdbfts {

    public static String[] readbook(String path, String book) throws Exception {

        DB.root(path);
        DB db = new DB(1);
        db.getConfig().ensureTable(new Ason("docid", 0L), "doc");

        final Engine engine = Engine.Instance;
        engine.Config(db.getConfig());

        final AutoBox auto = db.open();

        String[] ts = fileReader.read(book, (txt) -> {
            try (Box box = auto.cube()) {
                long docid = box.newId();
                box.d("doc").insert(new Ason(
                        "docid:", docid,
                        "info:", txt));
                engine.indexText(box, docid, txt, false);
                CommitResult cr = box.commit();
                cr.Assert();
            }
            return 1;
        });

        db.close();

        return ts;

    }

    public static Object[] searchbook_engine(String path) throws Exception {
        DB.root(path);
        DB db = new DB(1);
        final Engine engine = Engine.Instance;
        engine.Config(db.getConfig());
        //default is 512 cache
        //DatabaseConfig config = db.getConfig();
        //config.CacheLength = config.mb(512);
        final AutoBox auto = db.open();
        return new Object[]{auto, engine};
    }

    public static void searchbook_engine_close(Object[] args) throws Exception {
        ((AutoBox) args[0]).getDatabase().close();
    }

    public static ConcurrentLinkedQueue<Local> searchbook(Object[] args, int count, int topn, String keywords) throws Exception {

        final AutoBox auto = (AutoBox) args[0];
        final Engine engine = (Engine) args[1];

        final ConcurrentLinkedQueue<Local> list = new ConcurrentLinkedQueue<>();
        int r = fileReader.search(count, keywords, (txt) -> {
            int searchCount = 0;
            try (Box box = auto.cube()) {
                for (KeyWord kw : engine.searchDistinct(box, txt, Long.MAX_VALUE, topn)) {
                    long docid = kw.I;
                    Local doc = box.d("doc", docid).select();
                    list.add(doc);
                    searchCount++;
                }
            }
            return searchCount;
        });

        return list;
    }
}
